#include <stdio.h>
#include <string.h>

#include <unistd.h>
#include <limits.h>

#include <sys/socket.h>
#include <sys/types.h>
#include <netinet/in.h>
#include <poll.h>

#ifndef OPEN_MAX
#define OPEN_MAX 255
#endif

typedef struct sockaddr_in sockaddr_in;
typedef struct sockaddr sockaddr;

int main()
{
	int max_indx;
	char rd_buf[4098] = {0};
	struct pollfd client[OPEN_MAX];
	int fd = socket(AF_INET, SOCK_STREAM, 0);

	struct sockaddr_in addr;
	addr.sin_family = AF_INET;
	addr.sin_addr.s_addr = htonl(INADDR_ANY);
	addr.sin_port = htons(62400);

	bind(fd, (sockaddr*)&addr, sizeof(sockaddr_in));
	listen(fd, 10);

	client[0].fd = fd;
	client[0].events = POLLRDNORM;

	int i;
	for( i= 1; i < OPEN_MAX; ++i)
	{
		client[i].fd = -1;
	}
	max_indx = 0;

	while(1)
	{
		int ready_num = poll(client, max_indx + 1, 1000);

		if(client[0].revents & POLLRDNORM)
		{
			sockaddr_in peer_addr;
			int addr_len = sizeof(struct sockaddr);
			int peer_fd = accept(fd, (sockaddr *)&peer_addr, &addr_len);

			printf("recieve a connection\n");
			
			for(i = 1; i < OPEN_MAX; ++i)
			{
				if(client[i].fd < 0)
				{
					client[i].fd = peer_fd;
					client[i].events = POLLRDNORM;

					if(max_indx < i)
						max_indx = i;
					break;
				}
			}

			if(--ready_num <= 0)
				continue;
		}

		for(i = 1; i <= max_indx; ++i)
		{
			if( client[i].fd < 0)
				continue;

			if(client[i].revents & (POLLRDNORM | POLLERR))
			{
				int read_num = 0;
				if( (read_num = recv(client[i].fd, rd_buf, 1024, 0)) <= 0)
				{
					close(client[i].fd);
					client[i].fd = -1;
				}
				else
				{
					printf("%s\n", rd_buf);
				}

				if(--ready_num <= 0)
					break;
			}
		}	
	}

	return 0;
}